<template>
  <h4 class="lighter"><i class="ace-icon fa fa-hand-o-right icon-animated-hand-pointer blue"></i>
    <router-link to="/business/course" class="pink">{{ course.name }}</router-link>
  </h4>
  <hr>
  <!-- 课程 内容 -->
  <div class="">
    <div class="content">
      <BigFile
          :suffixs="['jpg', 'jpeg', 'png', 'mp4']"
          text="上传内容文件"
          :afterUpload="afterUploadContentFile"
          :use="FILE_TYPE.COURSE.key">
      </BigFile>
      <table id="simple-table" class="table table-bordered table-hover">
        <thead>
        <tr>
          <th>名称</th>
          <th>地址</th>
          <th>大小</th>
          <th>操作</th>
        </tr>
        </thead>

        <tbody>
        <tr v-for="file in courseContentFiles" :key="file.id">
          <td>{{ file.url }}</td>
          <td>{{ file.name }}</td>
          <td>{{ formatFileSize(file.size) }}</td>
          <td>
            <button @click="delFile(file)" class="btn btn-white btn-xs btn-warning btn-round">
              <i class="ace-icon fa fa-times red2"></i>
              删除
            </button>
          </td>
        </tr>
        </tbody>
      </table>

      <div class="modal-body">
        <form class="form-horizontal">
          <div class="form-group">
            <div class="col-sm-12">
              <div>{{ saveContentLabel }}</div>
            </div>
          </div>
          <div class="form-group">
            <div class="col-sm-12">
              <div id="content"></div>
            </div>
          </div>
        </form>
      </div>
      <button type="button" class="btn btn-primary">
        <router-link to="/business/course" class="white">返回课程</router-link>
      </button>
      &nbsp;
      <button @click="saveContent" type="button" class="btn btn-primary">保存</button>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import {onMounted, ref, onUnmounted } from "vue";
import {useRouter} from "vue-router";
import BigFile from "@/components/big-file";
import filter from "@/filter/filter";

export default {
  name: "CourseContent",
  components: {
    BigFile
  },
  setup() {
    const saveContentLabel = ref(''); // 自动保存内容提示文本
    const course = ref({}); // 课程信息
    const router = useRouter();
    const courseContentFiles = ref([]); // courseContentFiles 数组

    const FILE_TYPE = FILE_USE;

    let saveContentInterval = ref(); // 自动保存内容定时器

    // 获取课程内容文件列表
    const allCourseContentFile = () => {
      Loading.show();
      axios.post(process.env.VUE_APP_SERVER + "/business/admin/course-content-file/all",).then((response) => {
        Loading.hide();
        const resp = response.data;
        courseContentFiles.value = resp.content;
      })
    }

    /**
     * 保存 富文本
     */
    const saveContent = () => {
      // 获取富文本
      let content = $("#content").summernote("code");

      axios.post(process.env.VUE_APP_SERVER + "/business/admin/course/save-content", {
        id: course.value.id,
        content: content
      }).then((response) => {
        const resp = response.data;
        if (resp.success) {
          let nowTime = Tool.dateFormat("yyyy:MM:dd hh:mm:ss");
          saveContentLabel.value = "最后保存时间：" + nowTime;
        } else {
          Toast.error("内容保存失败!");
        }
      })
    }

    // 删除课程内容文件
    const delFile = (f) => {
      Confirm.show("删除后不可恢复，确认删除？", function () {
        Loading.show();
        axios.delete(process.env.VUE_APP_SERVER + "/business/admin/course-content-file/delete/" + f.id).then((response) => {
          const resp = response.data;
          if (resp.success) {
            Loading.hide();
            Tool.removeObj(courseContentFiles.value, f);
          }
        })
        Toast.success("删除成功");
      })
    }

    /**
     * 富文本初始化
     */
    const init = () => {
      $('#content').summernote({
        focus: true,
        height: 300
      });

      // 先清除富文本历史
      $('#content').summernote('code', '');
      saveContentLabel.value = '';

      // 获取富文本内容
      axios.get(process.env.VUE_APP_SERVER + "/business/admin/course/find-content/" + course.value.id).then((response) => {
        const resp = response.data;
        if (resp.success) {
          if (resp.content) {
            // 为富文本框 赋值
            $('#content').summernote('code', resp.content.content);

            // 自动保存 10s
            saveContentInterval.value = setInterval(() => {
              saveContent();
            },10000);
          } else {
            Toast.warning(resp.message);
          }
        }
      })
    }

    /**
     * 上传内容文件后，保存内容文件记录
     * response: 文件上传成功后返回的对象
     */
    const afterUploadContentFile = (response) => {
      console.log("开始保存文件记录");
      console.log(response)
      let file = {...response};
      file.courseId = course.value.id;
      file.url = file.path;
      axios.post(process.env.VUE_APP_SERVER + '/business/admin/course-content-file/save', file).then((response) => {
        let resp = response.data;
        if (resp.success) {
          Toast.success("上传文件成功");
          courseContentFiles.value.push(resp.content);
        }
      });
    }

    /**
     * 格式化文件大小
     */
    const formatFileSize = (size) => {
      return filter.formatFileSize(size);
    }

    onMounted(() => {
      let session_course = SessionStorage.get(SESSION_KEY_COURSE);
      if (Tool.isEmpty(session_course)) {
        router.push('/welcome');
        return;
      }
      course.value = session_course;
      init();

      allCourseContentFile();
    })

    /**
     * 清除定时器
     */
    onUnmounted(() => {
      console.log("自动保存内容定时器销毁");
      clearInterval(saveContentInterval.value);
    });

    return {
      course,
      courseContentFiles,
      saveContent,
      saveContentLabel,
      delFile,
      FILE_TYPE,
      afterUploadContentFile,
      formatFileSize
    }
  }
}
</script>

<style scoped>

</style>